/**
 * 版权所有(C) COVISINT 2015-2025
 * Copyright 2015-2025 COVISINT
 * 创建日期：Jun 29, 20172:29:30 PM
 * 创建人：yyang
 */
package com.wechat.framework.service;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.covisint.platform.GsonUtils.GsonUtils;
import com.covisint.platform.httpclient.domain.HttpResult;
import com.covisint.platform.httpclient.utils.HttpClientUtils;
import com.wechat.framework.messages.oauth.OAuthUser;
import com.wechat.framework.messages.push.req.FileReqMessages;
import com.wechat.framework.messages.push.req.ImageReqMessages;
import com.wechat.framework.messages.push.req.MpNewsReqMessages;
import com.wechat.framework.messages.push.req.NewsReqMessages;
import com.wechat.framework.messages.push.req.TextCardReqMessages;
import com.wechat.framework.messages.push.req.TextReqMessages;
import com.wechat.framework.messages.push.req.VideoReqMessages;
import com.wechat.framework.messages.push.req.VoiceReqMessages;
import com.wechat.framework.messages.push.resp.UploadTempFilesResp;
import com.wechat.framework.messages.token.AccessToken;
import com.wechat.framework.utils.WechatPushMessageUtils;
import com.wechat.framework.utils.WechatURLUtils;
import com.google.gson.reflect.TypeToken;

@Service
public class WechatSupportService {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private HttpClientUtils httpClientUtilsTemp;
	
	private static HttpClientUtils httpClientUtils;
	
	//通过该标签以及该方法实现给static属性注入
	@PostConstruct  
    public void init() {
		WechatSupportService.httpClientUtils = httpClientUtilsTemp;
    }  
	
	public static AccessToken getAccessToken(String corpID, String secret) {
		
		AccessToken accessToken = null;  
		  
	    String requestUrl = WechatURLUtils.ACCESS_TOKEN_URL.replace("CorpID", corpID).replace("SECRET", secret);
	    
	    try {
			String jsonResult = httpClientUtils.doGet(requestUrl);
			System.out.println(jsonResult);
			
			//返回结果不为空
			if(null != jsonResult){
				accessToken = GsonUtils.convert(jsonResult, new TypeToken<AccessToken>(){});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
 
	    return accessToken;
	}

	public static String findOAuth2GetUserIdByCode(String accessToken, String code, String agentId) {
		
		OAuthUser oauthUser = null;

		String requestUrl = WechatURLUtils.GET_OAUTH2_URL.replace("ACCESS_TOKEN", accessToken).replace("CODE", code);//.replace("AGENTID", agentId)
		
		try {
			String jsonResult = httpClientUtils.doGet(requestUrl);
			System.out.println(jsonResult);
			//返回结果不为空
			if(null != jsonResult){
				oauthUser = GsonUtils.convert(jsonResult, new TypeToken<OAuthUser>(){});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (null != oauthUser && oauthUser.getUserId() != null) {
			return oauthUser.getUserId();
		}

		return null;
	}
	
	/**
	 * 发送文本消息
	 * @param textMessage
	 * @param accessToken
	 * @return HttpResult
	 */
	public static HttpResult sendTextMessage(String url, TextReqMessages textMessage, String accessToken){
		//先将textMessage转成json字符串
		String json = WechatPushMessageUtils.textReqMessageToJson(textMessage);
		HttpResult httpResult = new HttpResult();
		try {
			httpResult = httpClientUtils.doPostJson(url,null,json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpResult;
	}
	
	/**
	 * 发送图片消息
	 * @param imageMessage
	 * @param accessToken
	 * @return HttpResult
	 */
	public static HttpResult sendImageMessage(ImageReqMessages imageMessage, String accessToken){
		String url = WechatURLUtils.SEND_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
		//先将imageMessage转成json字符串
		String json = WechatPushMessageUtils.imageReqMessageToJson(imageMessage);
		HttpResult httpResult = new HttpResult();
		try {
			httpResult = httpClientUtils.doPostJson(url,null,json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpResult;
	}
	
	/**
	 * 发送语音消息
	 * @param voiceMessage
	 * @param accessToken
	 * @return
	 */
	public static HttpResult sendVoiceMessage(VoiceReqMessages voiceMessage, String accessToken){
		String url = WechatURLUtils.SEND_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
		//先将voiceMessage转成json字符串
		String json = WechatPushMessageUtils.voiceReqMessageToJson(voiceMessage);
		HttpResult httpResult = new HttpResult();
		try {
			httpResult = httpClientUtils.doPostJson(url,null,json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpResult;
	}
	
	/**
	 * 发送视频消息
	 * @param videoMessage
	 * @param accessToken
	 * @return
	 */
	public static HttpResult sendVideoMessage(VideoReqMessages videoMessage, String accessToken){
		String url = WechatURLUtils.SEND_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
		//先将videoMessage转成json字符串
		String json = WechatPushMessageUtils.videoReqMessageToJson(videoMessage);
		HttpResult httpResult = new HttpResult();
		try {
			httpResult = httpClientUtils.doPostJson(url,null,json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpResult;
	}
	
	/**
	 * 发送文件消息
	 * @param fileMessage
	 * @param accessToken
	 * @return
	 */
	public static HttpResult sendFileMessage(String url, FileReqMessages fileMessage, String accessToken){
		//先将fileMessage转成json字符串
		String json = WechatPushMessageUtils.fileReqMessageToJson(fileMessage);
		HttpResult httpResult = new HttpResult();
		try {
			httpResult = httpClientUtils.doPostJson(url,null,json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpResult;
	}
	
	/**
	 * 发送文本卡片消息
	 * @param textCardMessage
	 * @param accessToken
	 * @return
	 */
	public static HttpResult sendTextCardMessage(TextCardReqMessages textCardMessage, String accessToken){
		String url = WechatURLUtils.SEND_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
		//先将textCardMessage转成json字符串
		String json = WechatPushMessageUtils.textCardReqMessageToJson(textCardMessage);
		HttpResult httpResult = new HttpResult();
		try {
			httpResult = httpClientUtils.doPostJson(url,null,json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpResult;
	}
	
	/**
	 * 发送图文消息(news)
	 * @param newsMessage
	 * @param accessToken
	 * @return
	 */
	public static HttpResult sendNewsMessage(NewsReqMessages newsMessage, String accessToken){
		String url = WechatURLUtils.SEND_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
		//先将textCardMessage转成json字符串
		String json = WechatPushMessageUtils.newsReqMessageToJson(newsMessage);
		HttpResult httpResult = new HttpResult();
		try {
			httpResult = httpClientUtils.doPostJson(url,null,json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpResult;
	}
	
	/**
	 * 发送图文消息(mpnews)
	 * @param mpNewsMessage
	 * @param accessToken
	 * @return
	 */
	public static HttpResult sendMpNewsMessage(MpNewsReqMessages mpNewsMessage, String accessToken){
		String url = WechatURLUtils.SEND_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
		//先将textCardMessage转成json字符串
		String json = WechatPushMessageUtils.mpNewsReqMessageToJson(mpNewsMessage);
		HttpResult httpResult = new HttpResult();
		try {
			httpResult = httpClientUtils.doPostJson(url,null,json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpResult;
	}
	
	/**
	 * 上传临时素材文件
	 * @param urlStr
	 * @param textMap
	 * @param fileMap
	 * @param contentType
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static UploadTempFilesResp formUpload(String urlStr, String filePathName, String type) {
      
	  //封装文件
      Map<String, String> textMap = new HashMap<String, String>();
      //可以设置多个input的name，value
      textMap.put("name", "media");
      textMap.put("type", type);
      //设置file的name，路径
      Map<String, String> fileMap = new HashMap<String, String>();
      fileMap.put("upfile", filePathName);
      
      String res = "";
      HttpURLConnection conn = null;
      // boundary就是request头和上传文件内容的分隔符
      String BOUNDARY = "---------------------------123821742118716"; 
      try {
          URL url = new URL(urlStr);
          conn = (HttpURLConnection) url.openConnection();
          conn.setConnectTimeout(5000);
          conn.setReadTimeout(30000);
          conn.setDoOutput(true);
          conn.setDoInput(true);
          conn.setUseCaches(false);
          conn.setRequestMethod("POST");
          conn.setRequestProperty("Connection", "Keep-Alive");
          conn.setRequestProperty("User-Agent",
                  "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
          conn.setRequestProperty("Content-Type",
                  "multipart/form-data; boundary=" + BOUNDARY);
          OutputStream out = new DataOutputStream(conn.getOutputStream());
          // text
          if (textMap != null) {
              StringBuffer strBuf = new StringBuffer();
              Iterator iter = textMap.entrySet().iterator();
              while (iter.hasNext()) {
                  Map.Entry entry = (Map.Entry) iter.next();
                  String inputName = (String) entry.getKey();
                  String inputValue = (String) entry.getValue();
                  if (inputValue == null) {
                      continue;
                  }
                  strBuf.append("\r\n").append("--").append(BOUNDARY)
                          .append("\r\n");
                  strBuf.append("Content-Disposition: form-data; name=\""
                          + inputName + "\"\r\n\r\n");
                  strBuf.append(inputValue);
              }
              out.write(strBuf.toString().getBytes());
          }
         // file
         if (fileMap != null) {
             Iterator iter = fileMap.entrySet().iterator();
             while (iter.hasNext()) {
                 Map.Entry entry = (Map.Entry) iter.next();
                 String inputName = (String) entry.getKey();
                 String inputValue = (String) entry.getValue();
                 if (inputValue == null) {
                     continue;
                 }
                 File file = new File(inputValue);
                 String filename = file.getName();
                 
                 //没有传入文件类型，同时根据文件获取不到类型，默认采用application/octet-stream
                String contentType = new MimetypesFileTypeMap().getContentType(file);
                 //contentType非空采用filename匹配默认的类型
                 if(!"".equals(contentType)){
                	 if (filename.toLowerCase().endsWith(".xls")) {
                         contentType = "application/vnd.ms-excel"; 
                     }else if (filename.toLowerCase().endsWith(".pdf")) {
                         contentType = "application/pdf"; 
                     }else if (filename.toLowerCase().endsWith(".doc")) {
                         contentType = "application/msword"; 
                     }else if (filename.toLowerCase().endsWith(".ppt")) {
                         contentType = "application/vnd.ms-powerpoint"; 
                     }else if (filename.toLowerCase().endsWith(".txt")) {
                         contentType = "text/plain"; 
                     }else if (filename.toLowerCase().endsWith(".png")) {
                         contentType = "image/png"; 
                     }else if (filename.toLowerCase().endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                         contentType = "image/jpeg";
                     }else if (filename.toLowerCase().endsWith(".gif")) {
                         contentType = "image/gif";
                     }else if (filename.toLowerCase().endsWith(".ico")) {
                         contentType = "image/image/x-icon";
                     }else if (filename.toLowerCase().endsWith(".mp4")) {
                         contentType = "video/mpeg4";
                     }
                 }
                 if (contentType == null || "".equals(contentType)) {
                     contentType = "application/octet-stream";
                 }
                 StringBuffer strBuf = new StringBuffer();
                 strBuf.append("\r\n").append("--").append(BOUNDARY)
                         .append("\r\n");
                 strBuf.append("Content-Disposition: form-data; name=\""
                         + inputName + "\"; filename=\"" + filename
                         + "\"\r\n");
                 strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                 out.write(strBuf.toString().getBytes());
                 DataInputStream in = new DataInputStream(
                         new FileInputStream(file));
                 int bytes = 0;
                 byte[] bufferOut = new byte[1024];
                 while ((bytes = in.read(bufferOut)) != -1) {
                     out.write(bufferOut, 0, bytes);
                 }
                 in.close();
             }
         }
         byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
         out.write(endData);
         out.flush();
         out.close();
         // 读取返回数据
         StringBuffer strBuf = new StringBuffer();
         BufferedReader reader = new BufferedReader(new InputStreamReader(
                 conn.getInputStream()));
         String line = null;
         while ((line = reader.readLine()) != null) {
             strBuf.append(line).append("\n");
         }
         res = strBuf.toString();
         reader.close();
         reader = null;
     } catch (Exception e) {
         System.out.println("发送POST请求出错。" + urlStr);
         e.printStackTrace();
     } finally {
         if (conn != null) {
             conn.disconnect();
             conn = null;
         }
     }
      //将返回的res转成对象
      UploadTempFilesResp uploadTempFilesResp = new UploadTempFilesResp();
      if(null!=res&&!"".equals(res.trim())){
    	  uploadTempFilesResp = GsonUtils.convert(res, new TypeToken<UploadTempFilesResp>(){});
      }
     return uploadTempFilesResp;
 }
	
}
